package cn.itcast.servlet.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import cn.itcast.service.StudentService;
import cn.itcast.service.impl.StudentServiceImpl;
import cn.itcast.vo.Student;

public class StudentLogin extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("username:" + username + "###" + "password:"
				+ password);
		StudentService studentService = new StudentServiceImpl();

		Student student = studentService.getStudentByUsername(username);
		if (student == null) {
			JSONObject obj = new JSONObject();
			try {
				obj.put("status", "fail");
				obj.put("result", "查无此学生");
				String json = obj.toString();
				System.out.println(json);
				out.write(json);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			if (!student.getPassword().equals(password)) {
				JSONObject obj = new JSONObject();
				try {
					obj.put("status", "fail");
					obj.put("result", "密码不正确");
					String json = obj.toString();
					System.out.println(json);
					out.write(json);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				JSONObject obj = new JSONObject();
				try {
					// 更新用户，将token_id与 学生id相对应
					String token_id = UUID.randomUUID().toString().replace("-",
							"");
					student.setToken_id(token_id);
					studentService.updateStudent(student);

					obj.put("status", "success");
					obj.put("result", "登录成功");
					obj.put("token_id", token_id);
					String json = obj.toString();
					System.out.println(json);
					out.write(json);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}

	}



}
